package com.example.vv.BaiduVoice;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.aip.asrwakeup3.core.mini.AutoCheck;
import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.example.vv.fragmentWork.utlis.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

public class BaiduVoice implements EventListener {
    private EventManager asr;
    protected boolean enableOffline = false; // 测试离线命令词，需要改成true
    Context context;
    Activity activity;


    public BaiduVoice(Activity activity, Context context) {
        this.activity = activity;
        this.context = context;
        initPermission();
    }

    /**
     * enableOffline设为true时，在onCreate中调用
     * 基于SDK离线命令词1.4 加载离线资源(离线时使用)
     */
    private void loadOfflineEngine() {
        Map<String, Object> s1 = new LinkedHashMap<String, Object>();
        s1.put(SpeechConstant.DECODER, 2);
        s1.put(SpeechConstant.ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH, "assets://baidu_speech_grammar.bsg");
        asr.send(SpeechConstant.ASR_KWS_LOAD_ENGINE, new JSONObject(s1).toString(), null, 0, 0);
    }

    private void initPermission() {
        // 基于sdk集成1.1 初始化EventManager对象
        asr = EventManagerFactory.create(context, "asr");
        // 基于sdk集成1.3 注册输出事件类
        asr.registerListener(this); //  EventListener 中 onEvent方法

        if (enableOffline) {
            loadOfflineEngine(); // 测试离线命令词请开启, 测试 ASR_OFFLINE_ENGINE_GRAMMER_FILE_PATH 参数时开启
        }

        String[] permissions = {
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        ArrayList<String> applyLists = new ArrayList<>();
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, permission)) {
                applyLists.add(permission);
                //进入这里代表没有权限
            }
        }
        String tmpList[] = new String[applyLists.size()];
        if (!applyLists.isEmpty()) {
            //请求权限
            ActivityCompat.requestPermissions(activity, applyLists.toArray(tmpList), 123);
        }

    }

    /**
     * 基于SDK集成2.2 发送开始事件
     * 点击录音按钮开始录音
     * 测试参数填在这里
     */
    public void onStartVoice() {
//        if (TextUtils.isEmpty(et.getText())) {
//            et.setText("");
//        }
        Map<String, Object> s1 = new LinkedHashMap<String, Object>();
        String event = null;
        event = SpeechConstant.ASR_START; // 开始录音

        if (enableOffline) {
            s1.put(SpeechConstant.DECODER, 2); //离在线的并行策略
        }
        // 基于SDK集成2.1 设置识别参数
        s1.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);


        (new AutoCheck(context, new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 100) {
                    AutoCheck autoCheck = (AutoCheck) msg.obj;
                    synchronized (autoCheck) {
                        String message = autoCheck.obtainErrorMessage(); // autoCheck.obtainAllMessage();
                        Log.w("AutoCheckMessage", message); //log中查看代码
                    }

                }
            }
        }, enableOffline)).checkAsr(s1);
        String json = null;
        json = new JSONObject(s1).toString();
        asr.send(event, json, null, 0, 0);


    }

    /**
     * 停止录音
     */
    public void onStopVoice() {
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
    }


    String result = "";
    @Override
    public void onEvent(String s, String s1, byte[] bytes, int i, int i1) {
        if (s.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
            // 识别相关的结果都在这里
            if (s1.contains("\"final_result\"")) {
                try {
                    JSONObject jsonObject = new JSONObject(s1);
                    result = jsonObject.getString("best_result");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        printLog(result);
    }

    /**
     * 输出语音识别结果
     *
     * @param text
     */
    String str = "";
    public String printLog(String text) {
        LogUtils.Log(text);
        str = text;
        onStopVoice();
        return str;
    }

    public String getRes() {
        String res = str;
        return res;
    }
}

